﻿#include "uploadOpenDoorInforThread.h"
#include "commonfuc.h"
#include "logfile.h"
#include "httpclient.h"
#include <QThread>
#include <QFileInfo>
#include <QTextCodec>

uploadOpenDoorInforThread::uploadOpenDoorInforThread()
{
    nTimeout = 5000;
    m_nUploadCount = 0;
    m_nHeartbeat = 0;
    m_Group = "openDoor_Infor";
    m_strHttpClientKeyName = QString("uploadOpenDoorInforThread");
    QTextCodec::codecForName("utf-8");//GBK
    m_strRecordDirPath = CommonFuc::getRecordPath();
    QString fileName = m_strRecordDirPath + "cache_infor.record";
    m_pRecord = new Settings(fileName,QSettings::IniFormat, this);
    m_pTimer = Q_NULLPTR;
}

uploadOpenDoorInforThread::~uploadOpenDoorInforThread()
{
    if(m_pTimer)
    {
        m_pTimer->stop();
        delete m_pTimer;
        m_pTimer = Q_NULLPTR;
    }

    if(m_pRecord)
    {
        delete m_pRecord;
        m_pRecord = Q_NULLPTR;
    }
}

void uploadOpenDoorInforThread::onInitPara(TRANSFER_INFO info)
{
    paraInfo = info;

    m_pTimer = new QTimer();
    m_pTimer->moveToThread(this->thread());
    connect(m_pTimer,SIGNAL(timeout()),this,SLOT(onTimeout()));
    m_pTimer->start(nTimeout);
}

void uploadOpenDoorInforThread::onTimeout()
{
    QString strLog;
    if(Q_NULLPTR == m_pTimer)
    {
        strLog = "***********uploadOpenDoorInforThread::onTimeout m_pTimer is NULL***********";
        logFile::printLog(strLog);
        return;
    }

    if(Q_NULLPTR == m_pRecord)
    {
        strLog = "***********uploadOpenDoorInforThread::onTimeout m_pRecord is NULL***********";
        logFile::printLog(strLog);
        return;
    }

    //Print heartbeat once a minute
    if(0 == m_nHeartbeat % 12)
    {
        strLog.sprintf("&&&&&&&&&&&& uploadOpenDoorInforThread::heartbeat(HeartbeatCount=%d.) &&&&&&&&&",(int)m_nHeartbeat);
        logFile::printLog(strLog);
    }

    QString key;
    QVariant value;
    if(m_pRecord->GetFirstNodeInfo(m_Group,key,value))
    {
        QString strValue = value.toString();
        if(!key.isEmpty() && !strValue.isEmpty())
        {
            m_pTimer->stop();
            strLog.sprintf("&&&&&&&&&&&& uploadOpenDoorInforThread Prepare for onRequestUploadInfor (UploadCount=%d) &&&&&&&&&",(int)m_nUploadCount);
            logFile::printLog(strLog);
            onRequestUploadInfor(key,strValue);
            m_pTimer->start(nTimeout);
            m_nUploadCount++;
        }
    }

    m_nHeartbeat++;
    return;
}

void uploadOpenDoorInforThread::onRequestUploadInfor(QString key, QString value)
{
    QString strLog;
    if(key.isEmpty() || value.isEmpty())
    {
        strLog = QString("onRequestUploadInfor::para is NULL!");
        logFile::printLog(strLog);
        return;
    }

    //QString("http://127.0.0.1:7887/UploadOpenDoorInfor");
    QString strUrl = "";
    strUrl.append(paraInfo.UploadInforUrl);

    HttpClient* pHttpFun = new HttpClient(m_strHttpClientKeyName);
    if(Q_NULLPTR == pHttpFun)
    {
        strLog = "onRequestUploadInfor::pHttpFun is NULL";
        logFile::printLog(strLog);
        return;
    }


    pHttpFun->setKeyAndValue(key,value);
    connect(pHttpFun,SIGNAL(signal_requestFinished(QString,int,bool,const QString&,int,QString,QString)),
            this,SLOT(slot_requestFinished(QString,int,bool,const QString&,int,QString,QString)));

    QByteArray content = value.toUtf8();
    pHttpFun->sendRequest_Post(strUrl,content,1);
    strLog.sprintf("--------upload opendoor information start:%s.",value.toStdString().c_str());
    logFile::printLog(strLog);
}

void uploadOpenDoorInforThread::slot_requestFinished(QString strHttpKey,int nType,bool bSuccess, const QString& strResult,int userData,QString strKey,QString strValue)
{
    if(strHttpKey != m_strHttpClientKeyName)
    {
        return;
    }

    Q_UNUSED(userData);

    QString strType;
    QString strIsSuccess;
    if(1==nType)
    {
        strType = QString("uploadOpenDoorInforThread::Get Rsp:");
    }
    else
    {
         strType = QString("uploadOpenDoorInforThread::Post Rsp:");
    }

    if(bSuccess)
    {
        strIsSuccess = QString(" success ");
    }
    else
    {
        strIsSuccess = QString(" failure ");
    }


    QString strLog = QString("--------%1%2%3 (%4)").arg(strType,strIsSuccess,strResult,strValue);
    logFile::printLog(strLog);

    bool bResultFail = false;
    if(false == bSuccess)
    {
        bResultFail = true;
    }
    else
    {
        //"ret":true
        //QString strSuccessText = "\"ret\":";
        //strSuccessText.append("true");
        QString strSuccessText = QString("is OK");

        int nBegin = strResult.indexOf(strSuccessText);
        if (-1 == nBegin)
        {
            bResultFail = true;
        }
        else
        {
            bResultFail = false;
        }
    }

    if(false == bResultFail)
    {
        //Delete the successful record information ...
        if(m_pRecord)
        {
            m_pRecord->remove(m_Group, strKey);
            strLog.sprintf("Remove open door information Record:key=%s;value=%s.",strKey.toStdString().c_str(),strValue.toStdString().c_str());
            logFile::printLog(strLog);
        }
    }

    return;

}
